package vip.ifmm.lehouse.api.gateway.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 操作Cookie的工具类
 *
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/16 20:50
 */
@Slf4j
public class CookieUtil {

    // Cookie过期时间 一天
    public static final int COOKIE_TIME_OUT = 3600 * 24;
    // Cookie的key
    public static final String COOKIE_KEY = "user_token";

    /**
     * 将token放入cookie中
     *
     * @param response 响应对象
     * @param token    token(redis的key)
     */
    public static void addCookie(HttpServletResponse response, String token) {
        // 将token放入cookie 之后用token去取redis中的对象
        Cookie cookie = new Cookie(COOKIE_KEY, token);
        // 设置过期时间
        cookie.setMaxAge(COOKIE_TIME_OUT);
        cookie.setPath("/");
        log.info(token + " 加入Cookie");
        response.addCookie(cookie);
    }

    /**
     * 获得指定Cookie的值
     *
     * @param request   请求
     * @param cookieKey Cookie的key
     * @return Cookie的值(token)
     */
    public static String getCookieValue(HttpServletRequest request, String cookieKey) {
        // 获得所有cookies
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            // 找到存储token的cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieKey)) {
                    // 返回token
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
